package database;

import java.util.ArrayList;

import model.GroupContacts;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class GroupContactsAdapter {
	
	private static final String TABLE_NAME2="group_contacts";
	public static final String KEY_ROWID = "_id";
	private static final String KEY_CONTACT="CONTACT_NAME";
	private static final String KEY_GROUPID="GROUP_ID";
	
	private static final String DATABASE_NAME = "groupsdb";
	private static final int DATABASE_VERSION = 1;
	private SQLiteDatabase db;
	private GroupHelper dbHelper;
	private Context ctx;
	
	public GroupContactsAdapter(Context ctx){
		this.ctx=ctx;
	}
	public GroupContactsAdapter open(){
		dbHelper = new GroupHelper(ctx, DATABASE_NAME, null, DATABASE_VERSION);
		db=dbHelper.getWritableDatabase();
		return this;
	}
	public void close(){
		dbHelper.close();
	}
	public long addContactToGroup(int grpId,String contactName){
		Log.d("GROUPSMS",contactName);
		ContentValues initialValues = new ContentValues();
	    initialValues.put(KEY_GROUPID, grpId);
	    initialValues.put(KEY_CONTACT, contactName);
	    return db.insert(TABLE_NAME2, null, initialValues);
	}
	public Cursor fetchAllContactsInGroup(int grpId){
		String colNames[]={KEY_ROWID,KEY_GROUPID,KEY_CONTACT};
		dbHelper.onCreate(db);
		Cursor allContacts =  db.query(TABLE_NAME2, colNames, KEY_GROUPID+'='+grpId, null, null, null, null);		
		return allContacts;
	}
	public boolean deleteContactInGroup(int contactId){
		return db.delete(TABLE_NAME2, KEY_ROWID+ '=' +contactId, null)>0;
	}
	public ArrayList<GroupContacts> fetchContacts(int grpId){
		ArrayList<GroupContacts> list=new ArrayList<GroupContacts>();
		Cursor c=fetchAllContactsInGroup(grpId);
		if(c!=null){
			while(c.moveToNext()){
				int id=c.getInt(c.getColumnIndexOrThrow(KEY_ROWID));
				String name=c.getString(c.getColumnIndexOrThrow(KEY_CONTACT));
				GroupContacts g=new GroupContacts(grpId,id,name);
				list.add(g);
			}
		}
		c.close();
		return list;
	}
	 
}
